package com.cy.store.service.impl;

import com.cy.store.entity.Cart;
import com.cy.store.entity.Product;
import com.cy.store.mapper.CartMapper;
import com.cy.store.mapper.ProductMapper;
import com.cy.store.service.CartService;
import com.cy.store.service.ex.AccessDeniedException;
import com.cy.store.service.ex.CartNotFoundException;
import com.cy.store.service.ex.InsertException;
import com.cy.store.service.ex.UpdateException;
import com.cy.store.vo.CartVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class CartServiceImpl implements CartService {
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private ProductMapper productMapper;

    @Override
    public List<CartVO> getVOByUid(Integer uid) {
        List<CartVO> voByUid = cartMapper.findVOByUid(uid);
        return voByUid;
    }

    @Override
    public Integer addNum(Integer cid, Integer uid, String username) {
        Cart result = cartMapper.findByCid(cid);
        if(result==null) throw new CartNotFoundException("数据不存在");
        if(!result.getUid().equals(uid)) throw new AccessDeniedException("数据非法访问");
        Integer num = result.getNum()+1;
        Integer row = cartMapper.updateNumByCid(cid, num, username, new Date());
        if(row!=1) throw new UpdateException("更新数据失败");
        return num;
    }

    @Override
    public List<CartVO> getVOByCid(Integer uid, Integer[] cids) {
        List<CartVO> list = cartMapper.findVOByCid(cids);
        //判断数据访问合法性，没有用
//        Iterator<CartVO> it = list.iterator();
//        while(it.hasNext()){
//            CartVO cartVO = it.next();
//            if(!cartVO.getUid().equals(uid)) list.remove(cartVO);
//        }

        return list;
    }

    @Override
    public void addtoCart(Integer uid, Integer pid, Integer num, String username) {
        Cart result = cartMapper.findByUidAndPid(uid,pid);
        Date date = new Date();
        if(result==null){ //从来没有加入购物车
            //创建一个cart
            Cart cart = new Cart();
            cart.setUid(uid);
            cart.setNum(num);
            cart.setPid(pid);

            Product product=productMapper.findById(pid);
            System.out.println(product.getPrice());
            cart.setPrice(product.getPrice());
            cart.setCreatedTime(date);
            cart.setModifiedTime(date);
            cart.setModifiedUser(username);
            cart.setCreatedUser(username);
            // 执行插入
            Integer row =cartMapper.insert(cart);
            if(row!=1)throw new InsertException("购物车数据插入异常");
        }else{// 已经在购物车中，更新num值
            Integer sumNum = result.getNum()+num;
            Integer row = cartMapper.updateNumByCid(result.getCid(),sumNum,username,date);
            if(row!=1)throw new UpdateException("修改购物车时出现异常");
        }
    }
}
